package hu.rsc.forbiddenwords.server.dictionary;

import hu.rsc.forbiddenwords.server.persistent.Entry;
import hu.rsc.forbiddenwords.server.persistent.PMF;

import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import javax.jdo.PersistenceManager;
import javax.jdo.Query;

import org.apache.commons.lang.StringUtils;

public class DictionaryWorker {
    public static final char SWAP = '*';
    HashMap<String, DictionaryEntry> entries = new HashMap<String, DictionaryEntry>();
    HashMap<DictionaryEntry, Integer> result = new HashMap<DictionaryEntry, Integer>();

    public DictionaryWorker(List<Long> dictionaryIds) {
	fillDictionary(dictionaryIds);
    }

    public String filter(String template) {
	String patternString = "(" + StringUtils.join(this.entries.keySet(), "|") + ")";
	Pattern pattern = Pattern.compile(patternString, Pattern.CASE_INSENSITIVE);
	Matcher matcher = pattern.matcher(template);

	StringBuffer sb = new StringBuffer();
	while (matcher.find()) {
	    DictionaryEntry entry = this.entries.get(matcher.group(1).toLowerCase());
	    matcher.appendReplacement(sb, entry.getSwap());
	    Integer count = this.result.get(entry);
	    if (count == null) {
		count = 0;
	    }
	    count++;
	    this.result.put(entry, count);
	}
	matcher.appendTail(sb);
	return sb.toString();
    }

    public void flushResult() {
	PersistenceManager pm = PMF.get().getPersistenceManager();

	Iterator<DictionaryEntry> iterator = this.result.keySet().iterator();
	while (iterator.hasNext()) {
	    DictionaryEntry e = iterator.next();
	    Entry entry = pm.getObjectById(Entry.class, e.getId());
	    entry.setCount(entry.getCount() + this.result.get(e));
	    pm.makePersistent(entry);
	    System.out.println(e.getString() + " : " + this.result.get(e) + " db");
	}
	pm.close();
    }

    private void fillDictionary(List<Long> dictionaryIds) {
	PersistenceManager pm = PMF.get().getPersistenceManager();

	Query query = pm.newQuery(Entry.class);
	/*query.setFilter("lastName == lastNameParam");
	query.setOrdering("hireDate desc");
	query.declareParameters("String lastNameParam");*/

	try {
	    List<Entry> results = (List<Entry>) query.execute();
	    if (!results.isEmpty()) {
		for (Entry e : results) {
		    this.entries.put(e.getWord().toLowerCase(), new DictionaryEntry(e.getKey().getId(), e.getWord().toLowerCase()));
		}
	    }
	} finally {
	    query.closeAll();
	    pm.close();
	}

    }
}
